package cn.jofei.client.netty;

import cn.jofei.common.config.AppProperties;
import cn.jofei.common.netty.protocol.MessageCodec;
import cn.jofei.common.thread.CommonEventLoop;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ds
 *
 * @author Jofei Bao
 * @version ngbao v1.0.
 * @date 2022年10月18日 11:29
 */
public abstract class SocketClient extends CommonEventLoop {

     static final Logger logger = LoggerFactory.getLogger(SocketClient.class);

    /**
     * 本地临时通道（用于提醒连接已创建）
     */
    private static final Map<Integer, Channel> TEMP_LOCAL_CHANNEL = new ConcurrentHashMap<>();

    static final String REMOTE_IP = AppProperties.get("server.domain");
    static final Integer SERVER_PORT = AppProperties.get("server.port", Integer.class).orElse(4443);

    /**
     * 消息协议编解码
     */
    static final MessageCodec MESSAGE_CODEC = new MessageCodec();
    /**
     * 日志打印
     */
    static final LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);

    public abstract void start();


    public static void saveChannel(int sequenceId, Channel local) {
        Channel channel = TEMP_LOCAL_CHANNEL.putIfAbsent(sequenceId, local);
        if (channel != null) {
            logger.error("本地临时通道添加失败，sequenceId: {}, current channel: {}", sequenceId, channel);
        }
    }

    public static void localChannelAutoRead(int sequenceId) {
        Channel channel = TEMP_LOCAL_CHANNEL.remove(sequenceId);
        if (channel != null) {
            logger.debug("本地临时通道开启自动读，sequenceId: {}", sequenceId);
            channel.config().setAutoRead(true);
        } else {
            logger.error("本地临时通道获取失败，sequenceId: {}", sequenceId);
        }
    }
}
